from pynput import keyboard, mouse
import time, json, asyncio

class ActionPlayer:
    def __init__(self):
        self.keyboard_controller = keyboard.Controller()
        self.mouse_controller = mouse.Controller()
        self.is_playing = False
        self.playback_speed = 1.0  # 1.0为正常速度，可以调整

    def load_events(self, filename):
        """从文件加载录制的事件"""
        with open(filename, 'r') as f:
            self.events = json.load(f)
        print(f"Loaded {len(self.events)} events from {filename}")
        return self.events

    def set_playback_speed(self, speed):
        """设置回放速度 (0.5为半速，2.0为双倍速)"""
        self.playback_speed = max(0.1, min(10.0, speed))  # 限制在0.1-10倍之间
    
    async def start(self, filename):
        self.load_events(filename)
        await self.play()

    async def play(self, events=None, repeat=1):
        """回放录制的事件"""
        if events is None:
            events = self.events
        
        if not events:
            print("No events to play")
            return

        self.is_playing = True
        
        for _ in range(repeat):
            if not self.is_playing:
                break
                
            start_time = None
            
            for event in events:
                if not self.is_playing:
                    break
                
                if start_time is None:
                    start_time = time.time() - event['time'] / self.playback_speed
                    continue
                
                # 计算应该等待的时间（考虑播放速度）
                current_time = time.time()
                expected_time = start_time + event['time'] / self.playback_speed
                wait_time = max(0, expected_time - current_time)
                await asyncio.sleep(wait_time)
                
                # 处理不同类型的事件
                self._handle_event(event)
        
        self.is_playing = False
        print("Playback completed")

    def stop(self):
        """停止回放"""
        self.is_playing = False

    def _handle_event(self, event):
        try:
            if event['type'] == 'key_press':
                key = self._str_to_key(event['key'])
                self.keyboard_controller.press(key)
            elif event['type'] == 'key_release':
                key = self._str_to_key(event['key'])
                self.keyboard_controller.release(key)
            elif event['type'] == 'mouse_move':
                self.mouse_controller.position = (event['x'], event['y'])
            elif event['type'] == 'mouse_click':
                button = self._str_to_button(event['button'])
                if event['pressed']:
                    self.mouse_controller.press(button)
                else:
                    self.mouse_controller.release(button)
            elif event['type'] == 'mouse_scroll':
                self.mouse_controller.scroll(event['dx'], event['dy'])
        except Exception as e:
            print(f"Error handling event: {e}")

    def _str_to_key(self, key_str):
        """将字符串转换为key对象"""
        if key_str.startswith('Key.'):
            return getattr(keyboard.Key, key_str[4:])
        elif key_str.startswith("'") and key_str.endswith("'"):
            return key_str[1:-1]
        return key_str

    def _str_to_button(self, button_str):
        """将字符串转换为button对象"""
        return getattr(mouse.Button, button_str.split('.')[-1])
